﻿using System;
using System.Linq;

namespace TempEmployees.DAL
{
    partial class Employee 
    {
        #region IFormattable Members & ToString()

        public override string ToString()
        {
            return this.ToString("G");
        }

        public string ToString(string format)
        {
            switch (format.ToUpperInvariant())
            {
                case "G":
                case "FN":
                    return string.Format("{0} {1}", FirstName, LastName);
                default:
                    throw new FormatException(String.Format("The {0} format string is not supported.", format));
            }
        }

        #endregion

        public Assignment CurrentAssignment { get { return GetCurrentAssignment(); } }
        public Assignment LatestAssignment { get { return GetLastAssignment(); } }

        private Assignment GetCurrentAssignment()
        {
            TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext();
            var assignment =
                from a in db.Assignments
                where a.StartDate <= DateTime.Now && a.EndDate >= DateTime.Now && a.EmployeeID == ID
                select a;
            return (assignment.Count() == 0) ? null : assignment.First();
        }

        private Assignment GetLastAssignment()
        {
            TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext();
            var assignment =
                from a in db.Assignments
                where a.EmployeeID == ID
                orderby a.StartDate descending
                select a;
            return (assignment.Count() == 0) ? null : assignment.First();
        }
    }
}
